package com.rds.workflow.controller;

import com.rds.common.annotation.Log;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.enums.BusinessType;
import com.rds.common.utils.SecurityUtils;
import com.rds.system.domain.*;
import com.rds.system.service.*;
import com.rds.workflow.domain.RdaWorkflowDynamicattribute;
import com.rds.workflow.domain.RdaWorkflowTemplete;
import com.rds.workflow.service.IRdaWorkflowDynamicattributeService;
import com.rds.workflow.service.IRdaWorkflowTempleteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 流程分类
 */
@RestController
@RequestMapping("/pms/workflowType")
public class WorkflowTypeController extends BaseController {

    @Autowired
    private IRdaTypeService rdaTypeService;

    @Autowired
    private IRdaWorkflowDynamicattributeService rdaWorkflowDynamicattributeService;

    @Autowired
    private IRdaFormService rdaFormService;

    @Autowired
    private IRdaFormDetailsService rdaFormDetailsService;

    @Autowired
    private IRdaCommandService rdaCommandService;

    @Autowired
    private IRdaSubcommandRelService rdaSubcommandRelService;

    @Autowired
    private IRdaToolbarService rdaToolbarService;

    @Autowired
    private IRdaWorkflowTempleteService rdaWorkflowTempleteService;

    /**
     * 查询流程分类
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:workflowTypeList')")
    @GetMapping("/workflowTypeList")
    public TableDataInfo workflowTypeList(){
        startPage();
        List<RdaType> list = rdaTypeService.selectRdaTypeLowerList("流程管理超类");
        for(RdaType type:list){
            String workflowName="";
            RdaWorkflowTemplete rdaWorkflowTemplete=new RdaWorkflowTemplete();
            rdaWorkflowTemplete.setAssignmentypeid(type.getId());
            List<RdaWorkflowTemplete> rdaWorkflowTempleteList=rdaWorkflowTempleteService.selectRdaWorkflowTempleteList(rdaWorkflowTemplete);
            for(RdaWorkflowTemplete workflowTemplete:rdaWorkflowTempleteList){
                workflowName+=workflowTemplete.getName()+",";
            }
            if(workflowName!=""){
                type.setWorkflowTempleteName(workflowName.substring(0,workflowName.length()-1));
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询流程分类下拉显示
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:workflowTypeTree')")
    @GetMapping("/workflowTypeTree")
    public TableDataInfo workflowTypeTree(){
        List<RdaType> list = rdaTypeService.selectRdaTypeLowerList("流程管理超类");
        Iterator<RdaType> iterator=list.iterator();
        while(iterator.hasNext()){
            if(iterator.next().getDescription().equals("流程管理超类")){
                iterator.remove();
            }
        }
        return getDataTable(list);
    }

    /**
     * 获取分类管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:modifyWorkflowType')")
    @GetMapping(value = "modifyWorkflowType/{id}")
    public AjaxResult modifyWorkflowType(@PathVariable("id") Long id)
    {
        return AjaxResult.success(rdaTypeService.selectRdaTypeById(id));
    }

    /**
     * 修改分类管理
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:modifyWorkflowType')")
    @PutMapping("/modifyWorkflowType")
    public AjaxResult modifyWorkflowTypeEdit(@RequestBody RdaType rdaType)
    {
        List<RdaType> typeList=rdaTypeService.selectRdaTypeList(new RdaType());
        for(RdaType type:typeList){
            if(type.getName().equals(rdaType.getName())){
                return error("请勿添加重复类型名称"+"'"+rdaType.getName()+"'");
            }
            if(type.getDescription().equals(rdaType.getDescription())){
                return error("请勿添加重复说明"+"'"+rdaType.getDescription()+"'");
            }
        }
        return toAjax(rdaTypeService.updateRdaType(rdaType));
    }
    /**
     * 删除分类管理
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:removeWorkflowType')")
    @DeleteMapping("/removeWorkflowType/{ids}")
    public AjaxResult removeWorkflowType(@PathVariable Long[] ids)
    {
        RdaType rdaType=new RdaType();
        rdaType.setId(ids[0]);
        rdaType.setStatus(0);
        int row=rdaTypeService.updateRdaType(rdaType);

        RdaType type=rdaTypeService.selectRdaTypeById(ids[0]);

        RdaForm rdaForm=new RdaForm();
        rdaForm.setName("add_"+type.getName());
        rdaForm.setDescription(type.getDescription());
        List<RdaForm> formList=rdaFormService.selectRdaFormList(rdaForm);
        rdaForm=new RdaForm();
        rdaForm.setId(formList.get(0).getId());
        rdaForm.setStatus(2);
        rdaFormService.updateRdaForm(rdaForm);

        RdaCommand rdaCommand=new RdaCommand();
        rdaCommand.setName("新增"+type.getDescription());
        rdaCommand.setUrl("/workflow/addWorkflow");
        List<RdaCommand> commandList=rdaCommandService.selectRdaCommandList(rdaCommand);
        rdaCommand=new RdaCommand();
        rdaCommand.setId(commandList.get(0).getId());
        rdaCommand.setStatus("0");
        rdaCommand.setUrl("/workflow/addWorkflow");
        rdaCommand.setPageParams(commandList.get(0).getPageParams());
        rdaCommandService.updateRdaCommand(rdaCommand);

        RdaToolbar rdaToolbar=new RdaToolbar();
        rdaToolbar.setName("myWorkflowInExecutionAdd");
        List<RdaToolbar> rdaToolbarList = rdaToolbarService.selectRdaToolbarList(rdaToolbar);
        RdaSubcommandRel rdaSubcommandRel=new RdaSubcommandRel();
        rdaSubcommandRel.setFromid(rdaToolbarList.get(0).getId().intValue());
        rdaSubcommandRel.setToid(commandList.get(0).getId().intValue());
        List<RdaSubcommandRel> subcommandRelList=rdaSubcommandRelService.selectRdaSubcommandRelList(rdaSubcommandRel);
        rdaSubcommandRel=new RdaSubcommandRel();
        rdaSubcommandRel.setId(subcommandRelList.get(0).getId());
        rdaSubcommandRel.setStatus("0");
        rdaSubcommandRelService.updateRdaSubcommandRel(rdaSubcommandRel);

        RdaWorkflowDynamicattribute rdaWorkflowDynamicattribute=new RdaWorkflowDynamicattribute();
        rdaWorkflowDynamicattribute.setTypeid(ids[0]);
        List<RdaWorkflowDynamicattribute> workflowDynamicattributeList=rdaWorkflowDynamicattributeService.selectRdaWorkflowDynamicattributeList(rdaWorkflowDynamicattribute);
        if(workflowDynamicattributeList!=null){
            for(RdaWorkflowDynamicattribute workflowDynamicattribute:workflowDynamicattributeList){
                rdaWorkflowDynamicattribute=new RdaWorkflowDynamicattribute();
                rdaWorkflowDynamicattribute.setId(workflowDynamicattribute.getId());
                rdaWorkflowDynamicattribute.setStatus("2");
                rdaWorkflowDynamicattributeService.updateRdaWorkflowDynamicattribute(workflowDynamicattribute);
            }
            RdaFormDetails rdaFormDetails=new RdaFormDetails();
            rdaFormDetails.setFormid(formList.get(0).getId());
            List<RdaFormDetails> formDetailsList=rdaFormDetailsService.selectRdaFormDetailsList(rdaFormDetails);
            for(RdaFormDetails formDetails:formDetailsList){
                rdaFormDetails=new RdaFormDetails();
                rdaFormDetails.setId(formDetails.getId());
                rdaFormDetails.setStatus("2");
                rdaFormDetailsService.updateRdaFormDetails(rdaFormDetails);
            }

        }
        return toAjax(row);
    }

    /**
     * 新增分类管理
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:addWorkflowType')")
    @Log(title = "流程分类管理", businessType = BusinessType.INSERT)
    @PostMapping("/addWorkflowType")
    @Transactional
    public AjaxResult add(@RequestBody RdaType rdaType)
    {
        List<RdaType> typeList=rdaTypeService.selectRdaTypeList(new RdaType());
        for(RdaType type:typeList){
            if(type.getName().equals(rdaType.getName())){
                return error("请勿添加重复类型名称"+"'"+rdaType.getName()+"'");
            }
            if(type.getDescription().equals(rdaType.getDescription())){
                return error("请勿添加重复说明"+"'"+rdaType.getDescription()+"'");
            }
        }
        RdaType rdaType2 = rdaTypeService.selectRdaTypeById(rdaType.getParentid());
        rdaType.setModuleName(rdaType2.getModuleName());
        rdaType.setTableName("rda_workflow");

        RdaForm rdaForm=new RdaForm();
        rdaForm.setName("add_"+rdaType.getName());
        rdaForm.setDescription(rdaType.getDescription());
        rdaFormService.insertRdaForm(rdaForm);

        RdaCommand rdaCommand=new RdaCommand();
        rdaCommand.setName("新增"+rdaType.getDescription());
        rdaCommand.setUrl("/workflow/addWorkflow");
        rdaCommand.setDescription("新增"+rdaType.getDescription());
        rdaCommand.setIcon("el-icon-plus");
        rdaCommand.setLocation("2");
        rdaCommand.setPageParams("{'handle':'handleAdd','addForm':'add_"+rdaType.getName()+"'}");
        rdaCommandService.insertRdaCommand(rdaCommand);

        RdaToolbar rdaToolbar=new RdaToolbar();
        rdaToolbar.setName("myWorkflowInExecutionAdd");
        List<RdaToolbar> rdaToolbarList = rdaToolbarService.selectRdaToolbarList(rdaToolbar);
        RdaSubcommandRel rdaSubcommandRel=new RdaSubcommandRel();
        rdaSubcommandRel.setFromid(rdaToolbarList.get(0).getId().intValue());
        rdaSubcommandRel.setFromtypeid(1);
        Set<Integer> commandIds = new HashSet<Integer>();
        commandIds.add(rdaCommand.getId().intValue());
        rdaSubcommandRel.setCommandIds(commandIds);
        rdaSubcommandRelService.insertRdaSubcommandRel(rdaSubcommandRel);
        return toAjax(rdaTypeService.insertRdaType(rdaType));
    }


    /**
     * 新增流程属性
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:addDynamicattribute')")
    @PostMapping("/addDynamicattribute")
    @Transactional
    public AjaxResult addDynamicattribute(@RequestBody RdaWorkflowDynamicattribute rdaWorkflowDynamicattribute, ServletRequest request){
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String wftypeid=httpRequest.getParameter("wftypeid");
        Long userId = SecurityUtils.getUserId();
        rdaWorkflowDynamicattribute.setStatus("1");
        rdaWorkflowDynamicattribute.setUpdateBy(String.valueOf(userId));
        rdaWorkflowDynamicattribute.setTypeid(Long.valueOf(wftypeid));
        rdaWorkflowDynamicattribute.setOwnerid(SecurityUtils.getUserId());

        RdaWorkflowDynamicattribute workflowDynamicattribute=new RdaWorkflowDynamicattribute();
        workflowDynamicattribute.setTypeid(Long.valueOf(wftypeid));
        workflowDynamicattribute.setIsDel(0);
        List<RdaWorkflowDynamicattribute> list = rdaWorkflowDynamicattributeService.selectRdaWorkflowDynamicattributeList(workflowDynamicattribute);
        RdaType rdaType=rdaTypeService.selectRdaTypeById(Long.valueOf(wftypeid));
        String name="add_"+rdaType.getName();
        RdaForm rdaForm=new RdaForm();
        rdaForm.setName(name);
        List<RdaForm> rdaFormList=rdaFormService.selectRdaFormList(rdaForm);

        RdaFormDetails formDetails=new RdaFormDetails();
        formDetails.setFormid(rdaFormList.get(0).getId());
        List<RdaFormDetails> formDetailsList=rdaFormDetailsService.selectRdaFormDetailsList(formDetails);

        RdaFormDetails rdaFormDetails=new RdaFormDetails();
        if(listContains(formDetailsList)==false){
            rdaFormDetails.setFormid(rdaFormList.get(0).getId());
            rdaFormDetails.setName("流程分类");
            rdaFormDetails.setDescription("流程分类");
            rdaFormDetails.setProp("typeid");
            rdaFormDetails.setDefaultValue(wftypeid);//默认值
            rdaFormDetails.setComponentType("el-select");
            rdaFormDetails.setSort(1);
            rdaFormDetails.setEditable(false);
            rdaFormDetails.setOptionValue("url:/workflowType/workflowTypeTree");
            rdaFormDetailsService.insertRdaFormDetails(rdaFormDetails);

            rdaFormDetails=new RdaFormDetails();
            rdaFormDetails.setFormid(rdaFormList.get(0).getId());
            rdaFormDetails.setName("名称");
            rdaFormDetails.setDescription("名称");
            rdaFormDetails.setProp("name");
            rdaFormDetails.setComponentType("el-input");
            rdaFormDetails.setSort(2);
            rdaFormDetails.setRequired(true);
            rdaFormDetails.setEditable(true);
            rdaFormDetailsService.insertRdaFormDetails(rdaFormDetails);

            rdaFormDetails=new RdaFormDetails();
            rdaFormDetails.setFormid(rdaFormList.get(0).getId());
            rdaFormDetails.setName("描述");
            rdaFormDetails.setDescription("描述");
            rdaFormDetails.setProp("description");
            rdaFormDetails.setComponentType("el-input");
            rdaFormDetails.setSort(3);
            rdaFormDetails.setEditable(true);
            rdaFormDetailsService.insertRdaFormDetails(rdaFormDetails);

            rdaFormDetails.setFormid(rdaFormList.get(0).getId());
            rdaFormDetails.setName("流程模板");
            rdaFormDetails.setDescription("流程模板");
            rdaFormDetails.setProp("flowTempleteid");
            rdaFormDetails.setComponentType("el-select");
            rdaFormDetails.setSort(4);
            rdaFormDetails.setOptionValue("url:/workflowMGMT/templateType/"+wftypeid);
            rdaFormDetails.setRequired(true);
            rdaFormDetails.setEditable(true);
            rdaFormDetailsService.insertRdaFormDetails(rdaFormDetails);


            rdaFormDetails=new RdaFormDetails();
            rdaFormDetails.setFormid(rdaFormList.get(0).getId());
            rdaFormDetails.setName(rdaWorkflowDynamicattribute.getDescription());
            rdaFormDetails.setDescription(rdaWorkflowDynamicattribute.getDescription());
            rdaFormDetails.setProp(rdaWorkflowDynamicattribute.getAttributeName());
            rdaFormDetails.setDefaultValue(rdaWorkflowDynamicattribute.getDefaultVal());
            rdaFormDetails.setComponentType("el-input");
            rdaFormDetails.setSort(list.size()+5);
            rdaFormDetails.setEditable(true);
            rdaFormDetailsService.insertRdaFormDetails(rdaFormDetails);
        }else{
            rdaFormDetails=new RdaFormDetails();
            rdaFormDetails.setFormid(rdaFormList.get(0).getId());
            rdaFormDetails.setName(rdaWorkflowDynamicattribute.getDescription());
            rdaFormDetails.setDescription(rdaWorkflowDynamicattribute.getDescription());
            rdaFormDetails.setProp(rdaWorkflowDynamicattribute.getAttributeName());
            rdaFormDetails.setDefaultValue(rdaWorkflowDynamicattribute.getDefaultVal());
            rdaFormDetails.setComponentType("el-input");
            rdaFormDetails.setSort(formDetailsList.size()+1);
            rdaFormDetails.setEditable(true);
            rdaFormDetailsService.insertRdaFormDetails(rdaFormDetails);
        }


        int rows=rdaWorkflowDynamicattributeService.insertRdaWorkflowDynamicattribute(rdaWorkflowDynamicattribute);
        return toAjax(rows);

    }


    /**
     * 查询流程属性
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:dynamicattributeList')")
    @GetMapping("/dynamicattributeList")
    public TableDataInfo dynamicattributeList(RdaWorkflowDynamicattribute rdaWorkflowDynamicattribute){
        startPage();
        List<RdaWorkflowDynamicattribute> list = rdaWorkflowDynamicattributeService.selectRdaWorkflowDynamicattributeList(rdaWorkflowDynamicattribute);
        return getDataTable(list);
    }

    /**
     * 根据分类类型查询流程属性
     */
    @GetMapping("/getWftypeid")
    public TableDataInfo getInfo( String wftypeid){
        startPage();
        RdaWorkflowDynamicattribute rdaWorkflowDynamicattribute=new RdaWorkflowDynamicattribute();
        rdaWorkflowDynamicattribute.setTypeid(Long.valueOf(wftypeid));
        rdaWorkflowDynamicattribute.setIsDel(0);
        List<RdaWorkflowDynamicattribute> list = rdaWorkflowDynamicattributeService.selectRdaWorkflowDynamicattributeList(rdaWorkflowDynamicattribute);
        return getDataTable(list);
    }

    /**
     * 删除流程属性
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:deleteWorkflowDynamicattribute')")
    @DeleteMapping("/deleteWorkflowDynamicattribute/{ids}")
    @Transactional
    public AjaxResult deleteWorkflowDynamicattribute(@PathVariable Long[] ids){
        RdaWorkflowDynamicattribute rdaWorkflowDynamicattribute=new RdaWorkflowDynamicattribute();
        rdaWorkflowDynamicattribute.setIsDel(2);
        rdaWorkflowDynamicattribute.setId(ids[0]);

        RdaWorkflowDynamicattribute workflowDynamicattribute=rdaWorkflowDynamicattributeService.selectRdaWorkflowDynamicattributeById(ids[0]);
        RdaType type=rdaTypeService.selectRdaTypeById(workflowDynamicattribute.getTypeid());

        RdaForm rdaForm=new RdaForm();
        rdaForm.setName("add_"+type.getName());
        rdaForm.setDescription(type.getDescription());
        List<RdaForm> formList=rdaFormService.selectRdaFormList(rdaForm);
        if(formList!=null && formList.size()!=0) {
            RdaFormDetails rdaFormDetails = new RdaFormDetails();
            rdaFormDetails.setFormid(formList.get(0).getId());
            rdaFormDetails.setDescription(workflowDynamicattribute.getDescription());
            rdaFormDetails.setProp(workflowDynamicattribute.getAttributeName());
            List<RdaFormDetails> formDetailsList = rdaFormDetailsService.selectRdaFormDetailsList(rdaFormDetails);
            for (RdaFormDetails formDetails : formDetailsList) {
                rdaFormDetails = new RdaFormDetails();
                rdaFormDetails.setId(formDetails.getId());
                rdaFormDetails.setStatus("2");
                rdaFormDetailsService.updateRdaFormDetails(rdaFormDetails);
            }
        }
        return toAjax(rdaWorkflowDynamicattributeService.updateRdaWorkflowDynamicattribute(rdaWorkflowDynamicattribute));
    }

    /**
     * 获取流程属性详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:dynamicattributeList')")
    @GetMapping(value = "dynamicattributeList/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(rdaWorkflowDynamicattributeService.selectRdaWorkflowDynamicattributeById(id));
    }

    /**
     * 修改流程属性
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:dynamicattributeList')")
    @PutMapping("/dynamicattributeList")
    @Transactional
    public AjaxResult modifyWorkflowList(@RequestBody RdaWorkflowDynamicattribute rdaWorkflowDynamicattribute){
        return AjaxResult.success(rdaWorkflowDynamicattributeService.updateRdaWorkflowDynamicattribute(rdaWorkflowDynamicattribute));
    }

    /**
     * 流程分类指定流程模板
     */
    @PreAuthorize("@ss.hasPermi('pms:workflowType:appointWorkflowTemplete')")
    @PostMapping("/appointWorkflowTemplete")
    @Transactional
    public AjaxResult appointWorkflowTemplete(@RequestBody RdaWorkflowTemplete rdaWorkflowTemplete){
            rdaWorkflowTemplete.setId(Long.valueOf(rdaWorkflowTemplete.getIds()));
            rdaWorkflowTemplete.setAssignmentypeid(rdaWorkflowTemplete.getToid());
            int row=rdaWorkflowTempleteService.updateRdaWorkflowTemplete(rdaWorkflowTemplete);
            return toAjax(row);
    }

    public static boolean listContains(List<RdaFormDetails> list) {
        for(RdaFormDetails formDetails:list){
            if("typeid".equals(formDetails.getProp()) || "name".equals(formDetails.getProp()) || "description".equals(formDetails.getProp())){
                return true;
            }
            return false;
        }
        return false;
    }
}
